<template>
  <div class="app-msg-add">
    <h4 class="title">
      <el-button type="text" icon="el-icon-back" style="color: #9a9a9a" @click="$router.go(-1)" />
      新增消息
    </h4>
    <Form ref="notice" v-model="model" :config="config" style="padding-top: 10px">
      <!-- 通知频次 -->
      <template #triggerFrequency>
        <el-radio-group v-model="model.triggerFrequency">
          <el-radio :label="false">仅触发后一次</el-radio>
          <el-radio :label="true">
            每天一次，每天
            <el-input-number class="ipt-number" :controls="false" :min="0" :max="23" v-model="model.triggerFrequencyTime" />
            点检查
          </el-radio>
        </el-radio-group>
      </template>

      <!-- 通知时间 -->
      <template #notifications>
        <el-checkbox-group v-model="model.notifications">
          <el-checkbox label="1">触发后立即通知</el-checkbox>
          <el-checkbox label="2">
            触发后超过
            <el-input-number class="ipt-number" :controls="false" :min="0" :max="3600" v-model="model.timedNotificationAfterTriggeringTime" />
            分钟后进行通知
          </el-checkbox>
        </el-checkbox-group>
      </template>

      <!-- 额外用户 -->
      <template #additionalUser>
        <el-select-tree
          :organizationsId="organizationsId"
          :valueMultiple="valueMultiple"
          :multiple="true"
          :clearable="true"
          @getValue="getSelectedValue"
        ></el-select-tree>
      </template>

      <!-- 通知模版 -->
      <template #notificationTemplates>
        <div class="tips">点击字段标签可以加入到模版内</div>
        <el-tag class="field-tag" type="info" v-for="tag in fields" :key="tag" @click="handleTagClick(tag)">{{ tag }}</el-tag>
        <div class="msg-tamplates">
          <table class="tpl-table" v-for="(item, index) in templates" :key="index">
            <tr>
              <td rowspan="3" class="label">
                {{ notification[item.notificationMethodType] }}
              </td>
              <td class="bg">
                <el-input v-model="item.title" maxlength="20" show-word-limit :disabled="isDisabled(item)"></el-input>
              </td>
            </tr>
            <tr>
              <td class="content">
                <el-input
                  :ref="`table_${index}`"
                  type="textarea"
                  v-model="item.content"
                  maxlength="100"
                  show-word-limit
                  :rows="5"
                  :disabled="isDisabled(item)"
                  @blur="handleBlurEvent($event, index)"
                ></el-input>
              </td>
            </tr>
            <tr>
              <td class="btn"><el-button @click="getMethodsDefault(item)" :disabled="isDisabled(item)">恢复默认</el-button></td>
            </tr>
          </table>
        </div>
      </template>
    </Form>

    <div class="btns">
      <el-button @click="$router.go(-1)">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script>
import Form from '@/components/Form'
import ElSelectTree from './components/select-tree'
import { notification_method_type } from '@/utils/dictOptions'
import { getNoticeDefault, addNoticeConfig } from '@/api/message'
export default {
  name: 'MessageAdd',
  components: {
    Form,
    ElSelectTree,
  },
  data: function () {
    return {
      blurIndex: null, //记录光标位置
      blurTableIndex: null,
      fields: ['单据创建人', '客户名称', '客户跟进的下次联系时间'],
      templates: [],
      model: { notifications: [] },
      config: [
        {
          label: '消息等级',
          prop: 'messageGrade',
          type: 'select',
          style: { width: '480px' },
          options: [],
          async: this.dictMessageGrade,
          rules: [
            {
              required: true,
              trigger: 'change',
              message: '请选择消息等级',
            },
            {
              required: true,
              validator: this.validMessageGradeNoticeBusinessType,
              trigger: ['change', 'blur'],
            },
          ],
        },
        {
          label: '通知业务',
          prop: 'noticeBusinessType',
          required: true,
          type: 'select',
          style: { width: '400px' },
          slotTitle: '消息通知设置',
          options: [],
          async: this.dictMessageBusiness,
          rules: {
            required: true,
            trigger: 'change',
            message: '请选择通知业务',
          },
        },
        {
          label: '通知名称',
          prop: 'noticeName',
          required: true,
          style: { width: '40%' },
          type: 'input',
          rules: {
            required: true,
            trigger: 'change',
            message: '请输入通知名称',
          },
        },
        {
          label: '通知频次',
          prop: 'triggerFrequency',
          required: true,
          render: true,
          rules: [
            {
              required: true,
              validator: this.validTriggerFrequency,
              trigger: 'change',
            },
          ],
        },
        {
          label: '通知时间',
          prop: 'notifications',
          required: true,
          render: true,
          rules: [
            {
              required: true,
              validator: this.validNotificationAfter,
              trigger: ['blur'],
            },
          ],
        },
        {
          label: '触发条件',
          prop: 'triggerConditions',
          type: 'checkbox',
          required: true,
          defaultProps: {
            label: 'name',
            value: 'value',
          },
          options: [],
          rules: {
            required: true,
            trigger: 'blur',
            message: '请选择触发条件',
          },
        },
        {
          label: '是否启用',
          prop: 'enable',
          type: 'radio',
          options: [
            { label: '启用', value: true },
            { label: '禁用', value: false },
          ],
        },
        {
          label: '默认用户',
          prop: 'defaultUser',
          required: true,
          slotTitle: '消息通知范围',
          type: 'checkbox',
          defaultProps: {
            label: 'name',
            value: 'value',
          },
          options: [],
          rules: {
            required: true,
            trigger: 'blur',
            message: '请选择默认用户',
          },
        },
        {
          label: '额外用户',
          prop: 'additionalUser',
          style: { width: '100%' },
          render: true,
        },
        {
          label: '通知方式',
          prop: 'notificationMethod',
          required: true,
          slotTitle: '通知内容',
          type: 'checkbox',
          options: notification_method_type,
          rules: {
            required: true,
            trigger: 'blur',
            message: '请选择通知方式',
          },
        },
        {
          label: '通知模版',
          prop: 'notificationTemplates',
          type: 'checkbox',
          render: true,
          style: { marginBottom: '0px' },
        },
      ],
      organizationsId: null,
      valueMultiple: [],
      // 默认用户选项
      defaultUserOptions: [],
      // 默认模版数据
      defaultTamplate: null,
      // 校验消息等级通知业务是否匹配
      validMessageGradeNotices: true,
    }
  },
  computed: {
    notification: function () {
      let obj = {}
      notification_method_type.forEach(item => {
        obj[item.value] = item.label
      })
      return obj
    },
    isDisabled: function () {
      return item => {
        const ids = this.model.notificationMethod
        if (ids && ids.length) {
          const enble = ids.includes(item.notificationMethodType)
          this.$set(item, 'enable', enble)
          return !enble
        } else {
          return true
        }
      }
    },
  },
  watch: {
    ['model.noticeBusinessType']: {
      handler: async function (nval) {
        if (nval != null || nval != undefined) {
          await this.getNoticeDefault({
            noticeBusinessType: nval,
            messageGrade: this.model.messageGrade,
          })
          this.$refs.notice.validateField('messageGrade')
        }
      },
    },
    ['model.messageGrade']: {
      handler: async function (nval) {
        if (nval != null || nval != undefined) {
          if (this.model.noticeBusinessType) {
            await this.getNoticeDefault({
              noticeBusinessType: this.model.noticeBusinessType,
              messageGrade: nval,
            })
          }
          this.$refs.notice.validateField('messageGrade')
        }
      },
    },
  },
  mounted() {
    this.templates = this.createTemplates()
  },
  methods: {
    async getNoticeDefault(params) {
      for (let i in params) {
        params[i] !== 0 && !params[i] && delete params[i]
      }
      return getNoticeDefault(params).then(res => {
        if (res.status && res.status === 204) {
          // this.$message.error('提交时判断消息等级是否匹配通知业务')
          this.validMessageGradeNotices = false
          res = {}
        } else {
          this.validMessageGradeNotices = true
        }
        this.model = Object.assign({}, this.model, res)
        this.model.defaultUser = []
        this.model.triggerConditions = []
        if (res.notificationAfterTriggering) {
          this.model.notifications.push('1')
        }
        if (res.timedNotificationAfterTriggering) {
          this.model.notifications.push('2')
          this.model.timedNotificationAfterTriggeringTime = res.timedNotificationAfterTriggeringTime
        }
        this.defaultTamplate = JSON.stringify(res.notificationTemplates)
        this.templates = res.notificationTemplates
          ? res.notificationTemplates.map(tpl => {
              return { ...tpl, enable: false }
            })
          : this.createTemplates()
        // 默认用户
        this.defaultUserOptions = res.defaultUser
          ? res.defaultUser.map((item, index) => {
              return { label: item.name, value: index }
            })
          : []
        // 触发条件
        this.triggerConditionsOptions = res.triggerConditions
          ? res.triggerConditions.map((item, index) => {
              return { label: item.name, value: index }
            })
          : []
        this.$set(
          this.config.find(i => i.prop == 'defaultUser'),
          'options',
          this.defaultUserOptions
        )
        this.$set(
          this.config.find(i => i.prop == 'triggerConditions'),
          'options',
          this.triggerConditionsOptions
        )
      })
    },
    handleSave() {
      this.$refs.notice.validate().then(valid => {
        if (!valid) return
        let defaultUser = []
        let additionalUser = []
        let triggerConditions = []
        let notificationMethod = []
        // 默认用户
        this.defaultUserOptions.forEach((item, index) => {
          if (this.model.defaultUser.includes(index)) defaultUser.push({ name: item.label, value: 'true' })
        })
        // 通知方式
        notification_method_type.forEach((item, index) => {
          if (this.model.notificationMethod.includes(item.value)) notificationMethod.push({ name: item.label, value: 'true' })
        })
        // 通知时间数据
        this.model.notificationAfterTriggering = this.model.notifications.includes('1')
        this.model.timedNotificationAfterTriggering = this.model.notifications.includes('2')
        // 触发条件数据
        this.triggerConditionsOptions.forEach((item, index) => {
          if (this.model.triggerConditions.includes(index)) triggerConditions.push({ name: item.label, value: 'true' })
        })
        // 额外用户
        additionalUser = this.model.additionalUser.map(item => {
          return { name: item.name, value: 'true', id: item.value }
        })
        // 提交
        addNoticeConfig({
          messageGrade: this.model.messageGrade,
          noticeBusinessType: this.model.noticeBusinessType,
          noticeName: this.model.noticeName,
          triggerFrequency: this.model.triggerFrequency,
          triggerFrequencyTime: this.model.triggerFrequencyTime,
          notificationAfterTriggering: this.model.notificationAfterTriggering,
          timedNotificationAfterTriggering: this.model.timedNotificationAfterTriggering,
          timedNotificationAfterTriggeringTime: this.model.timedNotificationAfterTriggeringTime,
          triggerConditions: triggerConditions,
          enable: this.model.enable,
          defaultUser: defaultUser,
          additionalUser: additionalUser,
          notificationTemplates: this.model.notificationTemplates,
        }).then(res => {
          this.$message.success('新增成功')
          this.$router.go(-1)
        })
      })
    },
    handleBlurEvent(e, index) {
      this.blurTableIndex = index
      this.blurIndex = e.srcElement.selectionStart
    },
    handleTagClick(text) {
      const index = this.blurIndex
      let str = this.templates[this.blurTableIndex].content
      let str_result = str.slice(0, index) + `[${text}]` + str.slice(index)
      if (str_result.length > 100) {
        this.$message.info('文字限制在100字以内')
        return
      }
      this.templates[this.blurTableIndex].content = str_result
      this.model.notificationTemplates = this.templates
    },
    getSelectedValue(value) {
      this.model.additionalUser = value.map(item => {
        return { name: item.name, value: item.id }
      })
    },
    getMethodsDefault(item) {
      const { messageType } = item,
        defaultTamplate = JSON.parse(this.defaultTamplate),
        target = defaultTamplate.find(i => i['messageType'] == messageType)
      item.content = target['content']
      item.title = target['title']
    },
    validTriggerFrequency(rule, value, callback) {
      if (!value) {
        callback()
      } else if (!this.model.triggerFrequencyTime) {
        callback(new Error('请输入触发时间'))
      } else {
        callback()
      }
    },
    validNotificationAfter(rule, value, callback) {
      if (!value.length) {
        callback(new Error('请选择通知时间'))
      } else if (value.includes('2') && !this.model.timedNotificationAfterTriggeringTime) {
        callback(new Error('请选择触发超过时间'))
      } else {
        callback()
      }
    },
    validMessageGradeNoticeBusinessType(rule, value, callback) {
      if ((value !== null || value !== undefined) && this.validMessageGradeNotices) {
        callback()
      } else {
        callback(new Error('禁止使用配置'))
      }
    },
    // 消息等级字典
    async dictMessageGrade() {
      const arr = await this.$store.dispatch('dicts/dictMessageGrade')
      const result = arr.map(item => {
        return { label: item.name, value: item.id }
      })
      return result
    },
    // 通知业务字典
    async dictMessageBusiness() {
      const arr = await this.$store.dispatch('dicts/dictMessageBusiness')
      const result = arr.map(item => {
        return { label: item.name, value: item.id }
      })
      return result
    },
    createTemplates() {
      return notification_method_type.map(item => {
        return {
          title: '',
          content: '',
          enable: false,
          messageType: 0,
          label: item.label,
          notificationMethodType: item.value,
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.app-msg-add {
  width: 100%;
  padding: 10px 20px;
  box-sizing: border-box;
}

::v-deep.btns {
  margin: 50px 20px;
  .el-button {
    width: 96px;
  }
}

.tips {
  width: 100%;
  font-size: 14px;
  color: #666666;
  line-height: 36px;
  font-style: normal;
}

.msg-tamplates {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-top: 20px;
  box-sizing: border-box;
}
.field-tag {
  cursor: pointer;
  margin: 15px 10px 0 0;
  &:hover {
    background: $main-light-blur;
    color: #fff;
  }
}
.tpl-table {
  width: 45%;
  margin: 0 15px 20px 0px;
  border-collapse: collapse;
  border-right: 1.5px solid #d8d8d8;
  border-bottom: 1.5px solid #d8d8d8;
  td {
    border-left: 1.5px solid #d8d8d8;
    border-top: 1.5px solid #d8d8d8;
    font-size: 14px;
    color: #333333;
    line-height: 19px;
    font-style: normal;
    ::v-deep .el-textarea__inner {
      border: none;
    }
    &.btn {
      text-align: center;
      .el-button {
        border: none;
        background: none;
      }
    }
    &.label {
      width: 100px;
      padding: 0;
      text-align: center;
      vertical-align: middle;
      text-align: center;
      vertical-align: middle;
    }
    &.bg {
      ::v-deep .el-input__inner,
      ::v-deep .el-input__count-inner {
        background-color: #ededed;
        border: none;
        border-radius: 0;
      }
    }
    &.cont {
      height: 120px;
      vertical-align: text-top;
    }
  }
}
.title {
  font-size: 18px;
  margin: 0;
  margin-bottom: 10px;
  padding: 0 0 10px 0;
  border-bottom: 0.5px solid #d8d8d8;
  // color: $main-blue;
  .el-button {
    font-size: 20px;
    margin-right: 10px;
  }
}
.ipt-number {
  width: 50px;
  margin: 0 5px;
  ::v-deep .el-input__inner {
    height: 30px;
  }
}
::v-deep .item_messageGrade {
  .el-form-item__content .el-select {
    width: 250px;
  }
  .el-form-item__error {
    left: 260px;
    top: 50%;
    margin-top: -10px;
  }
}
::v-deep .item_noticeBusinessType {
  .el-form-item__content .el-select {
    width: 250px;
  }
}
::v-deep .el-radio__input.is-checked .el-radio__inner,
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  border-color: #0076ff;
  background: #0076ff;
}
::v-deep .el-radio__input.is-checked + .el-radio__label,
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #0076ff;
}
</style>
